package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.CheckGroupDao;
import com.itheima.dao.CheckItemDao;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    SetmealDao setmealDao;
    @Autowired
    CheckGroupDao checkGroupDao;
    @Autowired
    CheckItemDao checkItemDao;
    @Autowired
    JedisPool jedisPool;

    @Autowired
    FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")//从属性文件读取输出目录的路径
    private String outPutPath;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Setmeal> page = setmealDao.selectByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            setSetmealAndCheckGroup(setmeal.getId(), checkgroupIds);
        }
        //将图片名称保存到Redis
        savePic2Redis(setmeal.getImg());
        //新增套餐后需要重新生成静态页面
        generateMobileStaticHtml(setmeal.getId());
    }

    private void generateMobileStaticHtml(int id) {
        //准备模板文件中所需的数据
        List<Setmeal> list = setmealDao.findAll();
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(list);
        //生成套餐详情静态页面（单个）
        generateMobileSetmealDetailHtml(id);
    }

    /**
     * 生成套餐详情静态页面（单个）
     */
    private void generateMobileSetmealDetailHtml(int id) {
        Map<String, Object> map = new HashMap<>();
        map.put("setmeal", setmealDao.findById(id));
        generateHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + id + ".html", map);
    }

    /**
     * 生成静态页面
     */
    private void generateMobileStaticHtml() {
        //准备模板文件中所需的数据
        List<Setmeal> list = setmealDao.findAll();
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(list);
        //生成套餐详情静态页面（多个）
        generateMobileSetmealDetailHtml(list);
    }

    /**
     * 生成套餐列表静态页面
     */
    private void generateMobileSetmealListHtml(List<Setmeal> list) {
        Map<String, Object> map = new HashMap<>();
        map.put("setmealList", list);
        generateHtml("mobile_setmeal.ftl", "m_setmeal.html", map);
    }

    /**
     * 生成套餐详情静态页面（多个）
     */
    private void generateMobileSetmealDetailHtml(List<Setmeal> list) {
        for (Setmeal setmeal : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("setmeal", setmealDao.findById(setmeal.getId()));
            generateHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", map);
        }
    }

    public void generateHtml(String templateName, String htmlPageName, Map<String, Object> dataMap) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        BufferedWriter out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            File file = new File(outPutPath + "\\" + htmlPageName);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
            template.process(dataMap, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    @Override
    public Setmeal findById(int id) {
        return setmealDao.findById(id);
    }

    @Override
    public Map<String, List> getSetmealReport() {
        List list = setmealDao.getSetmealReport();
        for (Object o : list) {
            Map map = (Map) o;
            if (map.get("value") == null) {
                map.put("value", 0);
            }
        }
        HashMap<String, List> map = new HashMap<>();
        map.put("setmealCount", list);
        return map;
    }

    //将图片名称保存到Redis
    private void savePic2Redis(String pic) {
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, pic);
    }

    private void setSetmealAndCheckGroup(Integer id, Integer[] checkgroupIds) {
        Map<String, Integer> map = new HashMap<>();
        map.put("setmeal_id", id);
        for (Integer checkgroupId : checkgroupIds) {
            map.put("checkgroup_id", checkgroupId);
            setmealDao.setSetmealAndCheckGroup(map);
        }
    }
}
